package servlets;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RetrieveItemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String SECURITY_APPNAME = "Politecn-2c1c-4683-a770-019912d3cb8b";
	private static final String OP_NAME = "findItemsByProduct";
	private static final String SERVICE_VERS = "1.0.0";
	private static final String GLOBAL_ID = "EBAY-US";
	private static final String ENCODING = "JSON";
	private static final int MAX_RESULTS = 1;
	private static final String TYPE = "ReferenceID";
	private static final String SERVICE_URI = "http://svcs.ebay.com/services/search/FindingService/v1";
	
	private String apiCall;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		String productId = request.getParameter("id");
		
		apiCall = SERVICE_URI + "?OPERATION-NAME=" + OP_NAME +
				"&SERVICE-VERSION=" + SERVICE_VERS +
				"&SECURITY-APPNAME=" + SECURITY_APPNAME + 
				"&GLOBAL-ID=" + GLOBAL_ID +
				"&RESPONSE-DATA-FORMAT=" + ENCODING +
				"&REST-PAYLOAD" +
				"&paginationInput.entriesPerPage=" + MAX_RESULTS +
				"&productId.@type=" + TYPE +
				"&productId=" + productId;
		
		URL url;
		URLConnection connection;
		try {
			url = new URL(apiCall);
			connection = url.openConnection();
			
			String line, resp;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			
			while ((line = reader.readLine()) != null) {
	            builder.append(line);
	        }

	        resp = builder.toString();

	        response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			
			response.getWriter().write(resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
